//
//  RootTableViewController.m
//  UI_18 HomeWork  讲解 豆瓣网络请求 StoryBoard
//
//  Created by dllo on 16/1/29.
//  Copyright © 2016年 wyl. All rights reserved.
//

#import "RootTableViewController.h"

#import "OnlineMovieModel.h"
#import "MovieDetailTableViewCell.h"
#import "MovieDetailViewController.h"

@interface RootTableViewController ()

@property (nonatomic, strong) OnlineMovieModel *onlineMovieModel;

@end

@implementation RootTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//   调用网络请求
    [self sendRequest];
   
}

- (void)sendRequest {
    
    NSString *string = @"http://api.douban.com/v2/movie/nowplaying";
    NSURL *url = [NSURL URLWithString:string];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    //    3.设置request的数据包
    NSString *postString = @"app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";
    //    将字符串转换成data数据
    NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
    //    给request设置body体（要上传的内容）
    [request setHTTPBody:data];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
    if (data) {
            
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
        self.onlineMovieModel = [[OnlineMovieModel alloc] initWithDataSource:result];
//         网络数据返回的时候刷新tabelView
        
//        解决（ 刷新完之后白屏 按一下之后才显示内容 ）的方法
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//        });
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
     }
    }];
    [task resume];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
////#warning Incomplete implementation, return the number of sections
//    return 0;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return self.onlineMovieModel.entries.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MovieDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MovieDetailCellldentifier" forIndexPath:indexPath];
    
    MovieDetailModel *movie = self.onlineMovieModel.entries[indexPath.row];
    
    cell.mocieDetail = movie;
    // Configure the cell...
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    取消cell选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MovieDetailModel *mocel = self.onlineMovieModel.entries[indexPath.row];
    
    MovieDetailViewController *movieDetailViewController = [[MovieDetailViewController alloc] initWithMovieDetailModel:mocel];
    
    [self.navigationController pushViewController:movieDetailViewController animated:YES];
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
